import { _decorator, Button, Component, EditBox, Layout, Node, Toggle, ToggleContainer } from 'cc';
import { VirtualList } from './scrollview/VirtualList';
const { ccclass, property } = _decorator;

@ccclass('Controller')
export class Controller extends Component {

    @property(ToggleContainer)
    ListToggleContainer: ToggleContainer;

    @property(ToggleContainer)
    directionToggleContainer: ToggleContainer;

    @property(Node)
    listParent: Node;

    @property(EditBox)
    input: EditBox;

    @property(Button)
    btnJump: Button;

    start() {
        this.ListToggleContainer.toggleItems.forEach(e => {
            e.node.on("toggle", this.onListToggle, this);
        })

        this.directionToggleContainer.toggleItems.forEach(e => {
            e.node.on("toggle", this.onDirectionToggle, this);
        })

        this.btnJump.node.on("click", this.onJump, this);
    }

    onListToggle(toggle: Toggle) {
        this.ListToggleContainer.toggleItems.forEach((e, index1) => {
            if (e == toggle) {
                this.listParent.children.forEach((node, index2) => {
                    node.active = index1 == index2;
                    this.directionToggleContainer.node.active = index1 != 0;
                })
            }
        })
    }

    onDirectionToggle(toggle: Toggle) {
        let list = this.listParent.getComponentsInChildren(VirtualList);
        this.directionToggleContainer.toggleItems.forEach((e, index) => {
            if (e == toggle) {
                if (index < 2) {
                    list.forEach((e, index2) => {
                        if (index2 !== 0 && e.vertical && e.node.active) {
                            e.verticalDirection = index == 0 ? Layout.VerticalDirection.TOP_TO_BOTTOM : Layout.VerticalDirection.BOTTOM_TO_TOP;
                            e.initAnchor();
                            e.setData(e.dataList);
                            e.verticalDirection = index == 0 ? e.scrollToTop() : e.scrollToBottom();
                        }
                    })
                } else {
                    list.forEach(e => {
                        if (e.horizontal && e.node.active) {
                            e.horizontalDirection = index == 2 ? Layout.HorizontalDirection.LEFT_TO_RIGHT : Layout.HorizontalDirection.RIGHT_TO_LEFT;
                            e.initAnchor();
                            e.setData(e.dataList);
                            e.horizontalDirection = index == 2 ? e.scrollToLeft() : e.scrollToRight();
                        }
                    })
                }
            }
        })
    }

    onJump() {
        let index = +this.input.string || 0;
        let list = this.listParent.getComponentsInChildren(VirtualList).find(a => { return a.node.activeInHierarchy == true });
        list.scrollToIndex(index);
    }
}


